#include <STC89C5xRC.H>
#include "delay.h"
#include "key.h"
#include "at24c02.h"
#include "LCD1602.H"
#include "ds18b20.h"
#include "timer0.h"

float T,TSHOW;
char TLOW,THIGH;
unsigned char keynum;

void main()
{
	THIGH=at24c02_readbyte(0);
	TLOW=at24c02_readbyte(1);
	if(THIGH>125 || TLOW<-55 || THIGH<=TLOW)
	{
		THIGH=35;
		TLOW=15;
	}
	ds18b20_convertT();
	Delayms(1000);
	LCD_Init();
	LCD_ShowString(1,1,"T:");
	LCD_ShowString(2,1,"TH:");
	LCD_ShowString(2,9,"TL:");
	LCD_ShowSignedNum(2,4,THIGH,3);
	LCD_ShowSignedNum(2,12,TLOW,3);
	time0_init();

	while(1)
	{
		keynum=key();
		//温度读取和显示
		ds18b20_convertT();
		T=ds18b20_readT();
		if(T<0)
		{
			LCD_ShowChar(1,3,'-');
			TSHOW=-T;
		}
		else
		{
			LCD_ShowChar(1,3,'+');
			TSHOW=T;
		}
		LCD_ShowNum(1,4,TSHOW,3);
		LCD_ShowChar(1,7,'.');
		LCD_ShowNum(1,8,((unsigned long)(TSHOW*100))%100,2 );
	
		//阈值判断
		if(keynum)
		{
			if(keynum==1)
			{
				THIGH++;
				if(THIGH>=125){THIGH=125;}
			}
			if(keynum==2)
			{
				THIGH--;
				if(THIGH<=TLOW){THIGH++;}
			}
			if(keynum==3)
			{
				TLOW++;
				if(TLOW>=THIGH){TLOW--;}
			}
			if(keynum==4)
			{
				TLOW--;
				if(TLOW<-55){TLOW=-55;}
			}
			LCD_ShowSignedNum(2,4,THIGH,3);
			LCD_ShowSignedNum(2,12,TLOW,3);
			at24c02_writebyte(0,THIGH);
			at24c02_writebyte(1,TLOW);

		}
		if(T>THIGH)
		{
			LCD_ShowString(1,13,"OV:H");
		}
		else if(T<TLOW)
		{
			LCD_ShowString(1,13,"OV:L");
		}
		else
		{
			LCD_ShowString(1,13,"OV:N");
		}
	
	
	
	
	}

}

//定时器中断函数模板
void timer0_routine() interrupt 1
{
	static unsigned int t0count;
	TH0=64535/256;
	TL0=64535%256;
	t0count++;
	if(t0count>=20)
	{
		t0count = 0;
		key_loop();
	}
}
